package comp.wxapi.service;

import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import comp.wxapi.bean.BaseConfigBean;
import comp.wxapi.bean.Result;
import me.chanjar.weixin.common.bean.WxCardApiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpCardService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpCardServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpCardResult;
import weixin.popular.api.CardAPI;
import weixin.popular.bean.card.AbstractCard;
import weixin.popular.bean.card.Cash;
import weixin.popular.bean.card.CashCard;
import weixin.popular.bean.card.Discount;
import weixin.popular.bean.card.DiscountCard;
import weixin.popular.bean.card.GeneralCoupon;
import weixin.popular.bean.card.GeneralCouponCard;
import weixin.popular.bean.card.Gift;
import weixin.popular.bean.card.GiftCard;
import weixin.popular.bean.card.Groupon;
import weixin.popular.bean.card.GrouponCard;
import weixin.popular.bean.card.create.Create;
import weixin.popular.bean.card.create.CreateResult;
import weixin.popular.bean.card.get.GetResult;

@Service
public class CardService {
	
	@Autowired
	private MpService mpService;
	
	/**
	 * 卡券创建
	 * @param configBean
	 * @param data
	 * @param accessToken
	 * @return
	 */
	public Result<?> cardCreate(String data,String accessToken) {
		AbstractCard abstractCard = JSON.parseObject(data, AbstractCard.class);
		String cardType = abstractCard.getCardType();
		Create<AbstractCard> card = new Create<AbstractCard>();
		switch (cardType) {
			case "GROUPON"://团购券
				GrouponCard grouponCard = new GrouponCard();
				Groupon groupon = JSON.parseObject(data, Groupon.class);
				grouponCard.setGroupon(groupon);
				card.setCard(grouponCard);
				break;
			case "DISCOUNT"://折扣券
				DiscountCard discountCard = new DiscountCard();
				Discount discount = JSON.parseObject(data, Discount.class);
				discountCard.setDiscount(discount);
				card.setCard(discountCard);
				break;
			case "GIFT"://礼品券
				GiftCard giftCard = new GiftCard();
				Gift gift = JSON.parseObject(data, Gift.class);
				giftCard.setGift(gift);
				card.setCard(giftCard);
				break;
			case "GENERAL_COUPON"://优惠券
				GeneralCouponCard generalCouponCard = new GeneralCouponCard();
				GeneralCoupon generalCoupon = JSON.parseObject(data, GeneralCoupon.class);
				generalCouponCard.setGeneralCoupon(generalCoupon);
				card.setCard(generalCouponCard);
				break;
			case "CASH"://代金券
				CashCard cashCard = new CashCard();
				Cash cash = JSON.parseObject(data, Cash.class);
				cashCard.setCash(cash);
				card.setCard(cashCard);
				break;
		}
		CreateResult createResult = CardAPI.create(accessToken, card);
		return Result.ok(createResult.getErrmsg(),createResult.getCardId());
	}
	
	/**
	 * 卡券签名
	 * @param data
	 * @param configBean
	 * @return
	 * @throws me.chanjar.weixin.common.error.WxErrorException 
	 * @throws WxErrorException 
	 */
	public WxCardApiSignature signature(String data,BaseConfigBean configBean) throws WxErrorException {
		WxCardApiSignature wxCardApiSignature = JSON.parseObject(data, WxCardApiSignature.class);
		WxMpService wxMpService = mpService.wxMpService(configBean);
		WxMpCardService wxMpCardService = new WxMpCardServiceImpl(wxMpService);
		String[] optionalSignParam = new String[] {wxCardApiSignature.getCardId()};
		if(StringUtils.isNotEmpty(wxCardApiSignature.getCode())) {
			optionalSignParam  = Arrays.copyOf(optionalSignParam, optionalSignParam.length+1);
			optionalSignParam[optionalSignParam.length-1] = wxCardApiSignature.getCode();
		}
		if(StringUtils.isNotEmpty(wxCardApiSignature.getOpenId())) {
			optionalSignParam  = Arrays.copyOf(optionalSignParam, optionalSignParam.length+1);
			optionalSignParam[optionalSignParam.length-1] = wxCardApiSignature.getOpenId();
		}
		wxCardApiSignature = wxMpCardService.createCardApiSignature(optionalSignParam);
		return wxCardApiSignature;
	}
	
	/**
	 * 卡券code解密
	 * @param code
	 * @param configBean
	 * @return
	 * @throws WxErrorException
	 */
	public String decryptCode(String code,BaseConfigBean configBean) throws WxErrorException {
		WxMpService wxMpService = mpService.wxMpService(configBean);
		WxMpCardService wxMpCardService = new WxMpCardServiceImpl(wxMpService);
		return wxMpCardService.decryptCardCode(code);
	}
	
	/**
	 * 卡券核销
	 * @param data
	 * @param configBean
	 * @return
	 * @throws WxErrorException
	 */
	public String consumeCard(String data,BaseConfigBean configBean) throws WxErrorException {
		WxMpService wxMpService = mpService.wxMpService(configBean);
		WxMpCardService wxMpCardService = new WxMpCardServiceImpl(wxMpService);
		JSONObject jsonObject = JSON.parseObject(data);
		String result = "";
		if(jsonObject.containsKey("cardId")) {
			result = wxMpCardService.consumeCardCode(jsonObject.getString("code"), jsonObject.getString("cardId"));
		}else {
			result = wxMpCardService.consumeCardCode(jsonObject.getString("code"));
		}
		jsonObject = JSON.parseObject(result);
		if("ok".equals(jsonObject.getString("errmsg"))) {
			return JSON.toJSONString(Result.ok());
		}
		return JSON.toJSONString(Result.ok(jsonObject.getString("errmsg"), null));
	}
	
	/**
	 * 查询卡券详情
	 * @param cardId
	 * @param accessToken
	 * @return
	 */
	public String getCardDetail(String cardId,String accessToken) {
		GetResult<?> result = CardAPI.getByCardId(accessToken, cardId);
		AbstractCard card = result.getCard();
		return JSON.toJSONString(card);
	}
	
	/**
	 * 卡券code查询
	 * @param cardId
	 * @param code
	 * @param configBean
	 * @return
	 * @throws WxErrorException
	 */
	public Result<?> queryCardCode(String cardId,String code,BaseConfigBean configBean) throws WxErrorException {
		WxMpService wxMpService = mpService.wxMpService(configBean);
		WxMpCardService wxMpCardService = new WxMpCardServiceImpl(wxMpService);
		WxMpCardResult queryCardCode = wxMpCardService.queryCardCode(cardId, code, false);
		return Result.ok().addData("card", queryCardCode.getCard())
			.addData("userCardStatus", queryCardCode.getUserCardStatus())
			.addData("openId", queryCardCode.getOpenId())
			.addData("canConsume", queryCardCode.getCanConsume());
	}
	
	/**
	 * 卡券删除
	 * @param cardId
	 * @param accessToken
	 */
	public void cardDelete(String cardId,String accessToken) {
		CardAPI.deleteByCardId(accessToken, cardId);
	}
}
